package com.java.servlet.web.login.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginController
 */
@WebServlet (name = "/login/loginController")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final int INIT_LOGIN = 0;
	private static final int LOGIN_USER = 1;
	private static final int VALIDAR_REGS = 2;
	private Properties viewConfig;
	private Properties fieldConfig;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginController() {
		super.init();
		try {
			viewConfig = PropertiesUtils.getPropertiesFromFile(getServletContext().getResource("/WEB-INF/view-config.properties"));
			fieldConfig = PropertiesUtils.getPropertiesFromFile(getServletContext().getResource("/WEB-INF/form-config.properties"));
		} catch (MalformedURLException ex) {
			System.out.println("Error fatal, no se puedo cargar el archivo de configuracion de vistas." + ex);
		}
    }
    protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		int metodo = Integer.parseInt(request.getParameter("method"));
		try {
			switch (metodo) {
			case INIT_LOGIN:
				dispatcher = request.getRequestDispatcher(viewConfig.getProperty("users.starter"));
				dispatcher.forward(request, response);
				break;
			case LOGIN_USER:
				dispatcher = request.getRequestDispatcher(viewConfig.getProperty("compuline.inicio"));
				dispatcher.forward(request, response);
				break;
			case VALIDAR_REGS:
				log.info(jsonRecords);
				objJsonData = parseJson(jsonRecords);
				if (StringUtils.isBlank(objJsonData.getUser())) {
					errorUser = true;
					divs.add(getDivYMensaje(DIV_VAL_USER, "Ingrese un usuario valido."));
				}
				if (errorUser) {
					success = false;
				} else {
					divs.add(getDivYMensaje(DIV_VAL_USER, ""));
				}
				if (StringUtils.isBlank(objJsonData.getPassword())) {
					errorPass = true;
					divs.add(getDivYMensaje(DIV_VAL_PASS, "Ingrese un password valido."));
				}
				if (errorPass) {
					success = false;
				} else {
					divs.add(getDivYMensaje(DIV_VAL_PASS, ""));
				}
				if(success){
					if(loginService.existeUsuario(objJsonData) == 0){
						success = false;
						divs.add(getDivYMensaje(DIV_ERRS_DATA, "Usuario no existe."));
					}else{
						divs.add(getDivYMensaje(DIV_ERRS_DATA, ""));
//						dispatcher = request.getRequestDispatcher(viewConfig.getProperty("system.inicio"));
//						dispatcher.forward(request, response);
//						ServletContext sc = getServletContext();
//						response.sendRedirect(getServletContext()+viewConfig.getProperty("system.inicio"));
						//request.getRequestDispatcher(viewConfig.getProperty("users.starter"));
//						dispatcher.forward(request, response);
//						RequestDispatcher rs = response.sendRedirect(viewConfig.getProperty("system.inicio"));
//						rs.forward(request, response);
//						request.getRequestDispatcher(viewConfig.getProperty("init.welcome")).forward(request, response);
						/*
						 * sendRedirect
						 * RequestDispatcher rd = getServletContext().getRequestDispatcher("pagina.j sp");
rd.forward(request, response);  
						 *   request.setAttribute("message", message);
            request.getRequestDispatcher("/FirstJSP.jsp").forward(request, response);                
        }
						 * */
					}
				}
				break;
			}
		} catch (Exception e) {
			System.out.println("Error en LoginController " + e);
			e.printStackTrace();
		} 
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
